<template>
    <div class="callcenter-product-table-container">
        <div class="action-button-group">
            <el-dropdown trigger="click">
                <span class="el-dropdown-link cur-point">
                    {{ $t('common.base.moreOperator') }}
                    <i class="iconfont icon-fdn-select"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-if="isButtonDisplayed && canProductExport">
                        <div @click="exportProduct(true)">{{ $t('common.base.export') }}</div>
                    </el-dropdown-item>
                    <el-dropdown-item>
                        <div @click="jumpProductList">{{ $t('customer.detail.customerProductTable.jumpProductList') }}</div>
                    </el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
            <span class="el-dropdown-link cur-point" @click="showAdvancedSetting">
                {{ $t('common.base.choiceCol') }}
                <i class="iconfont icon-fdn-select"></i>
            </span>
        </div>

        <el-table v-loading="listLoading" stripe :data="productList" :highlight-current-row="false"
            header-row-class-name="common-list-table-header__v2" v-bind="extraAttrs">
            <template slot="empty">
                <BaseListForNoData v-show="!listLoading" table-type="smallTable" :notice-msg="$t('common.base.tip.noData')">
                </BaseListForNoData>
            </template>

            <el-table-column v-for="(column, index) in columns" v-if="column.show" :key="`${column.field}_${index}`"
                :label="column.label" :prop="column.field" :width="column.width"
                :class-name="column.field == 'name' ? 'customer-product-name-superscript-td' : ''"
                :sortable="column.sortable" :show-overflow-tooltip="column.field !== 'name'" :align="column.align">
                <template slot-scope="scope">
                    <template v-if="column.field === 'state'">
                        {{ scope.row[column.field] }}
                    </template>
                    <template v-else-if="column.field === 'name'">
                        <sample-tooltip :row="scope.row">
                            <template slot="content" slot-scope="{ isContentTooltip }">
                                <el-tooltip :content="scope.row[column.field]" placement="top"
                                    :disabled="!isContentTooltip">
                                    <a href="" :data-id="scope.row.id" @click.prevent="createProductTab(scope.row.id)"
                                        class="product-link">
                                        {{ scope.row[column.field] }}
                                    </a>
                                </el-tooltip>
                            </template>
                        </sample-tooltip>
                    </template>
                    <template v-else-if="column.field === 'updateTime'">
                        <template v-if="scope.row.latesetUpdateRecord">
                            <el-tooltip class="item" effect="dark" :content="scope.row.latesetUpdateRecord" placement="top">
                                <div @mouseover="showLatestUpdateRecord(scope.row)">
                                    {{ scope.row.updateTime | formatDate }}
                                </div>
                            </el-tooltip>
                        </template>
                        <template v-else>
                            <div @mouseover="showLatestUpdateRecord(scope.row)">
                                {{ scope.row.updateTime | formatDate }}
                            </div>
                        </template>
                    </template>
                    <template v-else-if="column.formType === 'address'">
                        {{ getAddress(scope.row.attribute[column.field]) }}
                    </template>
                    <template v-else-if="column.formType === 'location'">
                        {{ scope.row.attribute[column.field] && scope.row.attribute[column.field].address }}
                    </template>
                    <template v-else-if="column.field === 'createUser'">
                        {{ scope.row.createUser && scope.row.createUser.displayName }}
                    </template>
                    <template v-else-if="column.field === 'createTime'">
                        {{ scope.row.createTime | formatDate }}
                    </template>
                    <div v-else-if="column.formType === 'textarea'"
                        v-html="buildTextarea(scope.row.attribute[column.field])" @click="openOutsideLink"></div>

                    <template v-else-if="column.fieldName == 'linkmanName'">
                        {{ scope.row.linkman.name }}
                    </template>
                    <template v-else-if="column.fieldName == 'phone'">
                        {{ scope.row.linkman.phone }}
                    </template>

                    <template v-else-if="column.field == 'address' && scope.row[column.field]">
                        {{ getAddress(scope.row[column.field]) }}
                    </template>
                    <template v-else-if="column.field == 'linkman' && scope.row[column.field]">
                        {{ scope.row[column.field].name }}
                    </template>
                    <template v-else-if="column.field == 'productCompleteAddress'">
                        {{ scope.row.productCompleteAdd }}
                    </template>
                    <template v-else>
                        {{ $formatFormField(column, scope.row) }}
                    </template>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <BaseAddOnPagination :paginationInfo="paginationInfo" @pageJump="jump" @sizeChange="handleSizeChange" />

        <!-- <base-table-advanced-setting ref="advanced" @save="modifyColumnStatus" /> -->
        <!-- 选择列 -->
        <biz-select-column ref="advanced" mode="product" @save="modifyColumnStatus" />

        <!-- 导出 start-->
        <base-export-group ref="exportPanel" :storage-key="exportStorageKey" :alert="exportAlert" :columns="exportColumns"
            :build-params="buildExportParams" :group="true" :validate="null" :needchoose-break="false" method="post"
            :action="productListExport" :is-show-export-tip="isOpenData" />
        <!-- 导出 end-->
    </div>
</template>

<script>
import { getProductFields, getProductList } from '@src/api/ProductApi';
import { productListExport } from '@src/api/Export';
import { isOpenData, openAccurateTab } from '@src/util/platform';
import { getEnabledCardInfo } from '@src/api/SettingCusProApi';
import { checkButtonDisplayed, getRootWindow } from '@src/util/dom';
import { getSystemNormalSearchInputForLength } from '@model/utils/getSystemConfig.ts';
import { smoothQualityInfoFieldForTable } from '@service/QualityInfoService.ts';
import { convertQualityInfoRemoteDataToFormQualityInfoFieldValue } from '@service/QualityInfoService.ts';
import { filterProductSearchParamsInvalidProperty } from '@service/ProductService.ts';

import { formatDate } from 'pub-bbx-utils';
import { safeNewDate } from '@src/util/time';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum';
import StorageKeyEnum from '@model/enum/StorageKeyEnum';
import { formatAddress } from 'pub-bbx-utils';
import { LINK_REG } from '@src/util/validator.js';

export default {
    name: 'callcenter-product-table',
    props: {
        shareData: {
            type: Object,
            default: () => ({}),
        },
        initData: {
            type: Object,
            default: () => ({}),
        },
        extraAttrs: {
            type: Object,
            default: () => ({}),
        },
    },
    data() {
        return {
            exportStorageKey: StorageKeyEnum.CustomerProductExport,
            productListExport,
            isOpenData,
            isButtonDisplayed: checkButtonDisplayed(),
            enabledCardList: [],
            productList: [],
            columns: this.fixedColumns(),
            paginationInfo: {
                pageSize: 10,
                pageNum: 1,
                totalItems: 0,
            },
            dynamicProductFields: [],
            searchModel: {
                hasBindCustomer: -1, // 是否关联客户
                keyword: '',
                pageSize: 10,
                pageNum: 1,
                orderDetail: {},
                catalogState: '',
                moreConditions: {
                    conditions: [],
                },
            },
            listLoading: true,
        };
    },
    computed: {
        customerId() {
            return this.shareData.customer ? this.shareData.customer.id : '';
        },
        // 客户名称
        customerName() {
            return this.shareData.customer ? this.shareData.customer.name : '';
        },
        customerConfig() {
            return {
                fieldInfo: this.dynamicProductFields.sort((a, b) => a.orderId - b.orderId),
            };
        },
        auth() {
            return this.initData?.loginUser?.authorities || this.initData?.authorities;
        },
        canProductExport() {
            return this.auth?.PRODUCT_EXPORT;
        },
        exportColumns() {
            let arr = [...this.columns].map(field => {
                field.export = true;
                field.exportAlias = field.field;
                field.tableName = 'product';
                if (['customer', 'productTemplate', 'remindCount'].some(key => key === field.fieldName) || field.formType === 'info') {
                    field.export = false;
                } else {
                    field.export = true;
                }

                if (field.field === 'linkman') {
                    field.exportAlias = 'linkmanName';
                }

                if ('qrcodeId' == field.fieldName) {
                    field.export = Boolean(this.initData.productConfig.qrcodeEnabled);
                }

                if ('qrcodeId' == field.fieldName) {
                    field.export = Boolean(this.initData.productConfig.qrcodeEnabled);
                }

                if (field.field === 'qualityInfoStartTime') {
                    field.exportAlias = 'qualityStartTime';
                }

                if (field.field === 'qualityInfoEndTime') {
                    field.exportAlias = 'qualityEndTime';
                }

                if (field.field === 'qualityInfoStatus') {
                    field.exportAlias = 'qualityStatus';
                }

                return field;
            });

            // 导出子表单（服务商）
            let serviceSubField = [];
            this.columns.forEach(item => {
                if (item?.setting?.isSubForm) {
                    let columns = item.subFormFieldList || [];
                    columns.forEach(sub => {
                        sub.value = sub.fieldName;
                        sub.label = sub.displayName;
                        sub.field = sub.fieldName;
                        sub.export = true;
                    });
                    serviceSubField.push({
                        value: item.fieldName,
                        label: item.displayName,
                        columns,
                    });
                }
            });

            let arr_ = [
                {
                    label: this.$t('product.productMessage'),
                    value: 'productExport',
                    columns: arr.filter(item => item.tableName == 'product' && item.fieldName != 'serviceProviders'),
                },
                ...serviceSubField,
                ...this.enabledCardList,
            ];
            return arr_;
        },
    },
    filters: {
        formatTags({ customer }) {
            if (!customer) return '';
            if (!customer.tags || !customer.tags.length) return '';
            return customer.tags.map(t => t.tagName).join(' ');
        },
        formatDate(val) {
            if (!val) return '';
            return formatDate(val, 'YYYY-MM-DD HH:mm:ss');
        },
    },
    async mounted() {
        try {
            // 获取产品自定义字段
            let res = await getProductFields({ isFromSetting: false });
            this.dynamicProductFields = res.data || [];
        } catch (error) {
            console.error('callcenter-product-table fetch product fields error', error);
        }
        this.revertStorage();
        this.columns = this.buildTableColumn();
        this.fetchData();
        this.getEnabledCardInfo();
    },
    methods: {
        /**
         * 导出服务商子表单数据
         */
        buildSubExportData(fieldName, list = []) {
            if (list.length < 1) return {};
            return {
                [fieldName]: list,
            };
        },
        buildParams() {
            const systemTypes = ['customerManager', 'createUser', 'synergies', 'tags', 'addressDetail'];
            let sm = Object.assign({}, this.searchModel);

            sm.systemConditions = [
                {
                    operator: 'eq',
                    property: 'customerId',
                    value: this.customerId,
                },
            ];

            let params = {
                keyword: getSystemNormalSearchInputForLength(sm.keyword),
                pageSize: sm.pageSize,
                pageNum: sm.pageNum,
                catalogState: sm.catalogState,
                hasBindCustomer: sm.hasBindCustomer,
                systemConditions: sm.systemConditions || [],
                conditions: sm.conditions || [],
            };

            if (Object.keys(sm.orderDetail || {}).length) {
                params.orderDetail = sm.orderDetail;
            }

            const qualitySearchParams = {}; // buildQualityInfoSearchParams(params)
            const allParams = Object.assign(params, qualitySearchParams);

            params = filterProductSearchParamsInvalidProperty(allParams);

            return params;
        },
        /**
         * @description 构建导出参数
         * @return {Object} 导出参数
         */
        buildExportParams(checkedMap, ids, exportOneRow) {
            const { productExport, catalogExport, serviceProviders } = checkedMap;
            const Params = Object.assign({}, this.params);
            const rootWindow = getRootWindow(window);
            const { loginUser } = this.initData;

            let exportAll = !ids || !ids.length;
            const all = exportAll
                ? {
                    ...this.buildParams(),
                    productIds: this.selectedIds,
                    tagIds: loginUser.tagIds,
                    tenantId: JSON.parse(rootWindow._init).user.tenantId,
                }
                : {
                    productIds: this.selectedIds,
                    tagIds: loginUser.tagIds,
                    tenantId: JSON.parse(rootWindow._init).user.tenantId,
                };

            let params = {
                exportSearchModel: JSON.stringify({
                    ...all,
                    ...{
                        exportTotal: exportAll ? this.paginationInfo.totalItems : this.selectedIds.length,
                    },
                }),
            };

            // 附加
            let cardFieldChecked = [];
            let cardChecked = [];
            for (let key in checkedMap) {
                if (key.indexOf('annexChecked') !== -1) {
                    cardFieldChecked = [...cardFieldChecked, ...checkedMap[key]];
                    if (checkedMap[key].length > 0) cardChecked.push(key.split('#')[1]);
                }
            }

            /** ********************* *********************/
            // 产品信息
            let export_product = this.exportData(0, productExport);
            // 附加信息
            let export_card_field = cardFieldChecked.length ? this.exportData(3, cardFieldChecked, 'cardFieldChecked') : cardFieldChecked;

            // 子表单（服务商）
            let export_subFields = JSON.stringify(this.buildSubExportData('serviceProviders', serviceProviders));
            // 产品类型信息
            // let export_catalog = this.exportData(1, catalogExport)

            params['exportOneRow'] = exportOneRow;
            params['data'] = exportAll ? '' : this.selectedIds.join(',');
            // params["catalogExport"] = export_catalog.join(",");
            params['productExport'] = export_product.join(',');
            params['subFieldNameMap'] = export_subFields;
            params['cardChecked'] = cardChecked.join(',');
            params['cardFieldChecked'] = export_card_field
                .filter(item => {
                    return item;
                })
                .join(',');

            return params;
        },
        /**
         * 导出数据
         */
        exportData(number, list = [], type) {
            const export_list = this.exportColumns;
            if (!list.length) return [];
            if (number === 3) {
                let cardField = [];
                export_list
                    .filter((item, index) => {
                        return type === 'cardFieldChecked' ? item.value !== 'productExport' : index > 2;
                    })
                    .forEach(v => {
                        v.columns.forEach(item => {
                            cardField.push(item);
                        });
                    });
                return cardField
                    .map(v => {
                        let bool = list.some(item => {
                            if (v.exportAlias) {
                                return v.exportAlias === item;
                            }
                            return v.fieldName === item;
                        });
                        if (bool) {
                            return v.exportAlias ? v.exportAlias : v.fieldName;
                        }
                    })
                    .filter(item => {
                        return item;
                    });
            }

            return export_list[number].columns
                .map(v => {
                    let bool = list.some(item => {
                        if (v.exportAlias) {
                            return v.exportAlias === item;
                        }
                        return v.fieldName === item;
                    });
                    if (bool) {
                        return v.exportAlias ? v.exportAlias : v.fieldName;
                    }
                })
                .filter(item => {
                    return item;
                });
        },
        /**
         * @description 导出提示
         */
        exportAlert(result, params = {}) {
            this.$platform.alert(result.message);
        },
        exportProduct(exportAll) {
            // 默认导出全部
            let ids = [];
            let fileName = `${formatDate(safeNewDate(), 'YYYY-MM-DD')}产品数据.xlsx`;
            this.$refs.exportPanel.open(ids, fileName);
        },
        // 获取附加组件
        async getEnabledCardInfo() {
            try {
                let { result, code, message } = await getEnabledCardInfo({ cardType: 'product' });
                if (code === 0) {
                    this.enabledCardList = result.map((item, index) => {
                        item.fields = [
                            ...(item.fields || []),
                            ...[
                                {
                                    displayName: this.$t('product.list.operator'),
                                    fieldName: `cu_${item.id}`,
                                },
                                {
                                    displayName: this.$t('product.list.operateTime'),
                                    fieldName: `ct_${item.id}`,
                                },
                            ],
                        ];

                        let columns = item.fields
                            .filter(f => f.fieldName !== 'part') // 关联备件字段的【备件】不需要导出 fix bug 17897
                            .map((v, i) => {
                                return {
                                    export: true,
                                    label: v.displayName,
                                    exportAlias: v.fieldName,
                                    ...v,
                                };
                            });

                        return {
                            value: `annexChecked#${item.id}`,
                            label: `${this.$t('product.additionalComponents')}：${item.name}`,
                            inputType: item.inputType,
                            columns: columns.filter(f => !['attachment', 'separator', 'autograph', 'info'].includes(f.formType)),
                        };
                    });
                } else {
                    this.$message.error(message);
                }
            } catch (err) {
                console.error(err);
            }
        },
        jumpProductList() {
            const fromId = window.frameElement.getAttribute('id');
            openAccurateTab({
                type: PageRoutesTypeEnum.PageProduct,
                params: `customerId=${this.customerId}&customerName=${this.customerName}`,
                reload: true,
                fromId,
            });
        },
        getRelatedTask(field) {
            return Array.isArray(field) ? field.map(item => item.taskNo).join(',') : '';
        },
        // 处理人员显示
        getUserName(field, value) {
            // 多选
            if (Array.isArray(value)) {
                return value.map(i => i.displayName || i.name).join(',');
            }

            let user = value || {};
            return user.displayName || user.name;
        },
        getAddress(field) {
            return formatAddress(field);
        },
        createProductTab(productId) {
            let fromId = window.frameElement.getAttribute('id');
            openAccurateTab({
                type: PageRoutesTypeEnum.PageProductView,
                key: productId,
                params: 'noHistory=1',
                fromId,
            });
        },
        jump(pN) {
            this.paginationInfo.pageNum = pN;
            this.fetchData();
        },
        handleSizeChange(pageSize) {
            this.paginationInfo.pageSize = pageSize;
            this.paginationInfo.pageNum = 1;
            this.fetchData();
        },
        revertStorage() {
            const { pageSize, column_number } = this.getLocalStorageData();
            if (pageSize) {
                this.params.pageSize = pageSize;
            }
        },
        fetchData() {
            this.listLoading = true;
            const params = {
                customerId: this.customerId,
                pageNum: this.paginationInfo.pageNum,
                pageSize: this.paginationInfo.pageSize,
            };

            getProductList(params)
                .then(res => {
                    this.productList = (res?.list || []).map(product => {
                        product.createTime = formatDate(safeNewDate(product.createTime), 'YYYY-MM-DD HH:mm:ss');
                        return Object.assign(product, convertQualityInfoRemoteDataToFormQualityInfoFieldValue(product, true));
                    });
                    this.paginationInfo.totalItems = res.total;
                })
                .catch(e => console.error('fetchData product caught e', e))
                .finally(() => {
                    this.listLoading = false;
                });
        },
        showAdvancedSetting() {
            console.log(this.columns);
            this.$refs.advanced.open(this.columns);
        },
        // columns
        modifyColumnStatus(event) {
            let columns = event.data || [];
            let colMap = columns.reduce((acc, col) => (acc[col.field] = col) && acc, {});

            this.columns.forEach(col => {
                let newCol = colMap[col.field];
                if (null != newCol) {
                    this.$set(col, 'show', newCol.show);
                    this.$set(col, 'width', newCol.width);
                }
            });

            const showColumns = this.columns.map(c => ({
                field: c.field,
                show: c.show,
                width: c.width,
            }));
            this.saveDataToStorage('columnStatus', showColumns);
        },
        // common methods
        getLocalStorageData() {
            const dataStr = localStorage.getItem('customerProductListData') || '{}';
            return JSON.parse(dataStr);
        },
        saveDataToStorage(key, value) {
            const data = this.getLocalStorageData();
            data[key] = value;
            localStorage.setItem('customerProductListData', JSON.stringify(data));
        },
        showLatestUpdateRecord(row) {
            if (row.latesetUpdateRecord) return;
            getUpdateRecord({
                productId: row.id,
            })
                .then(res => {
                    if (!res || res.status) return;

                    this.page.list = this.page.list.map(c => {
                        if (c.id === row.id) {
                            c.latesetUpdateRecord = res.data;
                        }
                        return c;
                    });

                    this.matchSelected();
                })
                .catch(e => console.error('e', e));
        },
        buildTextarea(value) {
            return value
                ? value.replace(LINK_REG, match => {
                    return `<a href="javascript:;" target="_blank" url="${match}">${match}</a>`;
                })
                : '';
        },
        openOutsideLink(e) {
            let url = e.target.getAttribute('url');
            if (!url) return;
            if (!/http/gi.test(url)) return this.$platform.alert(this.$t('common.base.tip.confirmHttpProtocol'));
            this.$platform.openLink(url);
        },
        buildTableColumn() {
            const localStorageData = this.getLocalStorageData();
            let columnStatus = localStorageData.columnStatus || [];
            let localColumns = columnStatus.map(i => (typeof i == 'string' ? { field: i, show: true } : i)).reduce((acc, col) => (acc[col.field] = col) && acc, {});
            // 质保信息
            const qualityInfoField = (this.dynamicProductFields || []).filter(item => item.formType === 'quality_info') || [];
            // 一拆三拆开的质保信息
            const qualityInfoFieldSpecify =
                (smoothQualityInfoFieldForTable(qualityInfoField) || []).map(item => {
                    return {
                        label: item.displayName,
                        field: item.fieldName,
                        ...item,
                    };
                }) || [];
                
            let baseColumns = [...this.fixedColumns(), ...qualityInfoFieldSpecify];
            // todo： 后端需要提供“客户产品”的动态列
            let dynamicColumns = this.customerConfig.fieldInfo
                .filter(f => !f.isSystem && f.formType !== 'attachment' && f.formType !== 'separator' && f.formType !== 'info' && f.formType !== 'autograph')
                .map(field => {
                    let sortable = false;
                    let minWidth = null;

                    if (['date', 'datetime', 'number'].indexOf(field.formType) >= 0) {
                        sortable = 'custom';
                        minWidth = 100;
                    }

                    if (field.displayName.length > 4) {
                        minWidth = field.displayName.length * 20;
                    }

                    if (sortable && field.displayName.length >= 4) {
                        minWidth = 125;
                    }

                    if (field.formType === 'datetime') {
                        minWidth = 150;
                    }

                    return {
                        label: field.displayName,
                        field: field.fieldName,
                        formType: field.formType,
                        minWidth: typeof minWidth == 'number' ? minWidth : `${minWidth}px`,
                        sortable,
                        isSystem: field.isSystem,
                        ...field,
                    };
                });

            let columns = [...baseColumns, ...dynamicColumns].map(col => {
                let show = col.show === true;
                let width = col.width;
                let localField = localColumns[col.field];

                if (null != localField) {
                    width = typeof localField.width == 'number' ? `${localField.width}px` : '';
                    show = localField.show !== false;
                }

                col.show = show;
                col.width = width;
                col.type = 'column';

                return col;
            });

            return columns;
        },
        fixedColumns() {
            let arr = [
                {
                    label: this.$t('customer.detail.customerProductTable.table.label.name'),
                    field: 'name',
                    show: true,
                },
                {
                    label: this.$t('customer.detail.customerProductTable.table.label.serialNumber'),
                    field: 'serialNumber',
                    show: true,
                },
                {
                    label: this.$t('customer.detail.customerProductTable.table.label.type'),
                    field: 'type',
                    show: true,
                },
                {
                    label: this.$t('customer.detail.customerProductTable.table.label.linkman'),
                    field: 'linkman',
                    show: true,
                },
                {
                    label: this.$t('customer.detail.customerProductTable.table.label.address'),
                    field: 'productCompleteAddress',
                    show: true,
                },
                {
                    label: this.$t('customer.detail.customerProductTable.table.label.createTime'),
                    field: 'createTime',
                    show: true,
                    width: '150px',
                },
            ];

            return arr.map(x => {
                return {
                    displayName : x.label,
                    ...x
                }
            })
        },
    },
};
</script>

<style lang="scss">
.callcenter-product-table-container {
    padding: 16px;

    .action-button-group {
        display: flex;
        justify-content: flex-end;
        margin-bottom: 12px;
        padding: 0;
    }

    .fdn-select {
        float: right;
        margin-bottom: 10px;
        cursor: pointer;

        &:hover {
            color: $color-main;
        }
    }

    .product-link {
        @include fontColor();
    }
}

td.customer-product-name-superscript-td {
    padding: 0 !important;

    &>.cell {
        padding-left: 0 !important;
    }

    &>div {
        height: 43px;
        line-height: 43px !important;

        a {
            display: inline-block;
            height: 43px;
            line-height: 43px;
        }
    }
}</style>
